import dash
from dash import html, dcc
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from server import server  # <--- 导入 server.py 中定义的 Flask server

from flask import Flask,session,redirect,request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from urllib.parse import urlparse
from urllib.parse import parse_qs
from modules.bigscreen.layouts import layout as bigscreen_layout
# 导入其他页面布局，例如登录页
from modules.login import layouts as login_layout

# 添加branch布局导入
from modules.branch.layouts import layout as branch_layout

import base64

from modules.repair.layouts import create_repair_layout

from modules.repair.callbacks import register_repair_callbacks
from modules.maintain.layouts import maintain_layout

from modules.inspection.layouts import inspection_layout

from modules.system.layouts import change_password_layout, user_manage_layout
from modules.system.components import management_menu

# 导入设备详情页面的布局函数
from modules.equipment.detail_layout import create_detail_layout



from models import User

# 初始化应用
dash_app = dash.Dash(
    __name__,
    server=server,
    url_base_pathname='/dash/',
    external_stylesheets=[
    #     # '/static/css/equipment.css',
    #     # dbc.themes.BOOTSTRAP,
        '/static/css/bootstrap513.min.css',
        '/static/css/styles.css'  # 确保这行存在
    ],
    suppress_callback_exceptions=True
)

# 设置浏览器标签页标题
dash_app.title = "黄浦区医疗设备智慧监控云平台"



#  导入并注册回调函数


from modules.login.callbacks import register_callbacks as register_login_callbacks
register_login_callbacks(dash_app)
register_repair_callbacks(dash_app)

from modules.repair.callbacks2 import register_repair_respond_callbacks
register_repair_respond_callbacks(dash_app)

from modules.repair.callbacks3 import register_callbacks as register_repair_callbacks3
register_repair_callbacks3(dash_app)

from modules.repair.callbacks4 import register_repair_complete_callbacks
register_repair_complete_callbacks(dash_app)

from modules.repair.callbacks5 import register_callbacks as register_repair_callbacks5
register_repair_callbacks5(dash_app)

from modules.maintain.callbacks import register_maintain_callbacks
register_maintain_callbacks(dash_app)

from modules.inspection.callbacks import register_inspection_callbacks
register_inspection_callbacks(dash_app)


from modules.bigscreen.callback import register_callbacks as register_bigscreen_callbacks
register_bigscreen_callbacks(dash_app)

from modules.bigscreen.callback2 import register_callbacks as register_bigscreen_callbacks2
register_bigscreen_callbacks2(dash_app)

from modules.system.callbacks import register_callbacks as register_system_callbacks
register_system_callbacks(dash_app)



from modules.equipment.callbacks import register_callbacks as register_equipment_module_callbacks
register_equipment_module_callbacks(dash_app)

from modules.equipment.callbacks2 import register_callbacks as register_equipment_module_callbacks2
register_equipment_module_callbacks2(dash_app)

#页面导入

from modules.login.layouts import layout as login_layout

from modules.bigscreen.layouts import layout as bigscreen_layout

from modules.repair.layouts import create_repair_layout as repair_layout


from modules.system.components import management_menu

from modules.branch.layouts import get_layout as get_branch_layout


from modules.branch.callbacks1 import register_callbacks as register_branch_callbacks1
register_branch_callbacks1(dash_app)

from modules.branch.callbacks2 import register_callbacks as register_branch_callbacks2
register_branch_callbacks2(dash_app)

# 读取图片并转换为base64
image_path = "static/icon/leftup_logo.png"
encoded_image = ""
try:
    with open(image_path, 'rb') as f:
        encoded_image = base64.b64encode(f.read()).decode('ascii')
except Exception as e:
    print(f"无法加载图片: {str(e)}")

# 设置应用布局
dash_app.layout = html.Div([
    dcc.Location(id='url', refresh=False), # 用于主导航
    dcc.Location(id='url-device-detail', refresh=False), # 新增用于设备详情页跳转
    html.Div(id='navbar-container'),  # 创建一个容器用于条件显示导航栏
    html.Div(id='page-content')
])

# 添加一个新的回调来控制导航栏的显示


@dash_app.callback(
    Output('navbar-container', 'children'),
    [Input('url', 'pathname')] # 导航栏显示只依赖主 URL
)
def display_navbar(pathname):
    # 如果是登录页面或分支页面，不显示导航栏
    # print(f" p108 pathname: {pathname} ")
    if pathname == '/dash/login' or pathname == '/dash/' or pathname == '/dash' or pathname == '/dash/branch':
        return []
    else:
        # 判断当前页面
        def nav_style(target):
            if pathname == target:
                return {"color": "orange", "padding": "0 10px", "fontSize": "14px", "textDecoration": "none", "fontWeight": "bold"}
            else:
                return {"color": "white", "padding": "0 10px", "fontSize": "14px", "textDecoration": "none"}

        left_items = html.Div([
            html.Img(src=f"data:image/png;base64,{encoded_image}", height="50px", style={"display": "inline-block", "verticalAlign": "middle","animation": "pulse 5s infinite ease-in-out" }),
            html.Span("黄浦区卫生健康委员会", style={"fontSize": "18px", "fontWeight": "bold", "color": "#EEEEEE", "marginLeft": "8px", "verticalAlign": "middle"})
        ], style={"display": "flex", "alignItems": "center", "flex": "0 0 auto"})

        center_items = html.Div([
            html.Span("黄浦区医疗设备智慧监控云平台", style={
                "fontSize": "28px",
                "fontWeight": "bold",
                "letterSpacing": "8px",
                "textShadow": "0 0 8px #2196f3, 0 0 2px #fff",
                "textAlign": "center",
                "color": "#EEEEEE",
                "verticalAlign": "middle"
            })
        ], style={"flex": "1", "display": "flex", "justifyContent": "center", "alignItems": "center"})

        # 获取当前用户角色
        user_role = None
        user_id = session.get("user_id")
        if user_id:
            user = User.query.get(user_id)
            if user:
                user_role = user.role

        # 根据角色显示不同按钮
        if user_role == "user":
            right_items = html.Div([
                html.A("驾驶大屏", href="/dash/bigscreen", style=nav_style("/dash/bigscreen")),
                html.A("设备台账", href="/dash/equipment", style=nav_style("/dash/equipment")),
                html.A("退出登录", href="/dash/logout", style=nav_style("/dash/logout")),
                html.A("修改密码", href="/dash/change-password", style=nav_style("/dash/change-password")),
            ], style={"display": "None", "alignItems": "center"})
        else:  # admin 或其他角色
            right_items = html.Div([
                html.A("驾驶大屏", href="/dash/bigscreen", style=nav_style("/dash/bigscreen")),
                html.A("设备台账", href="/dash/equipment", style=nav_style("/dash/equipment")),
                html.A("维修记录", href="/dash/repair", style=nav_style("/dash/repair")),
                html.A("保养记录", href="/dash/maintain", style=nav_style("/dash/maintain")),
                html.A("巡检记录", href="/dash/inspection", style=nav_style("/dash/inspection")),
                html.A("退出登录", href="/dash/logout", style=nav_style("/dash/logout")),
                html.A("修改密码", href="/dash/change-password", style=nav_style("/dash/change-password")),
                management_menu,
            ], style={"display": "None", "alignItems": "center"})

        return dbc.Navbar(
            html.Div([
                html.Div(left_items, style={"flex": "0 0 auto", "minWidth": "260px", "zIndex": 2}),
                html.Div(center_items, style={
                    "position": "absolute",
                    "left": "50%",
                    "top": 0,
                    "transform": "translateX(-50%)",
                    "height": "100%",
                    "display": "flex",
                    "alignItems": "center",
                    "zIndex": 1
                }),
                html.Div(right_items, style={"flex": "0 0 auto", "minWidth": "400px", "marginLeft": "auto", "zIndex": 2})
            ], style={
                "position": "relative",
                "display": "flex",
                "alignItems": "center",
                "height": "90px",
                "width": "100%"
            }),
            color=None,
            dark=True,
            style={
                "height": "90px",
                "padding": "0 15px",
                "position": "relative",
                "background": "linear-gradient(90deg, #0d133d 0%, #233a7e 100%)",
                "borderBottom": "0",  # 彻底去除底部间隔
                "borderTop": "2px solid #2196f3",
                "boxShadow": "0 4px 12px rgba(33,150,243,0.2)"
            }
        )



from modules.equipment import init_equipment_module

@dash_app.callback(
    Output('page-content', 'children'),
    [Input('url', 'pathname'),
     Input('url', 'search'), # 监听主 URL 的 search 参数
     Input('url-device-detail', 'pathname'), # 监听新的设备详情 URL 的 pathname
     Input('url-device-detail', 'search')] # 监听新的设备详情 URL 的 search 参数
)
def display_page(pathname, search, detail_pathname, detail_search):
    # 使用 callback_context 来判断是哪个 Input 触发了回调
    ctx = dash.callback_context
    if not ctx.triggered:
        # 初始加载时，使用主 URL 的信息
        current_pathname = pathname
        current_search = search
    else:
        # 回调被触发时，判断是哪个 Input 触发的
        trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
        if trigger_id == 'url':
            current_pathname = pathname
            current_search = search
        elif trigger_id == 'url-device-detail':
            current_pathname = detail_pathname
            current_search = detail_search
        else:
             # Fallback to main url if trigger is unexpected
            current_pathname = pathname
            current_search = search
    # print(f" p259 current_pathname: {current_pathname} ")
    # 判断是否已登录
    if 'user_id' not in session:
        # 允许访问登录页
        if current_pathname in ['/dash/login']:
            return login_layout
        else:
            # 未登录访问其他页面，强制跳转到登录页
            return login_layout

    # 已登录，正常路由
    if current_pathname == '/dash/' :
        current_pathname = '/dash/login' # 修正：这里应该是判断后跳转，而不是直接修改pathname

    if  current_pathname == '/dash/login':
        return login_layout
    elif current_pathname == '/dash/equipment':
        return init_equipment_module(dash_app)  # 设备台账页面
    elif current_pathname == '/dash/repair':
        return repair_layout()
       
    elif current_pathname.startswith('/dash/equipment/repair/'): #扫码报修流程入口
        # print(f" p151 进入报修页面 pathname: {pathname} ")
        try:
            device_id = int(current_pathname.split('/')[-1])
            # print(f" p154 进入报修页面 device_id: {device_id} ")
            from modules.repair.layouts import create_repair_form_page2
            return create_repair_form_page2(device_id)
        except Exception:
            return html.Div("设备ID无效", style={'textAlign': 'center', 'marginTop': '50px'})
    elif current_pathname == '/dash/maintain':
        return maintain_layout([], [])
    elif current_pathname == '/dash/inspection':
        return inspection_layout([], [])
    elif current_pathname == '/dash/settings':
        return html.Div("系统设置页面 - 开发中")
    elif current_pathname == '/dash/bigscreen':
        return bigscreen_layout
    
    
    
    elif current_pathname.startswith('/dash/branch'):
        # 处理org_code参数
        org_code = session.get('org_code')
        # print(f"app p303 session：{session}，current_search:{current_search} ,current_pathname: {current_pathname} ")
        if current_search:
            from urllib.parse import parse_qs, unquote
            print(f"Original current_search: {current_search}") # 调试信息
            decoded_search = unquote(current_search)
            print(f"Decoded search: {decoded_search}") # 调试信息
            query_string = decoded_search.lstrip('?')
            print(f"Query string: {query_string}") # 调试信息
            parsed_query = parse_qs(query_string)
            org_code = parsed_query.get('org_code', [None])[0]
            print(f"Parsed org_code: {org_code}") # 调试信息
        
        # 将org_code存储到session中
        if org_code and org_code != 'None':  # 同时检查是否为字符串'None'
            session['current_org_code'] = org_code
        # print(f" p311 session['current_org_code']:{session.get('current_org_code')} ") 
        return get_branch_layout()  # 调用函数而不是直接返回变量
        
    elif current_pathname == '/dash/change-password':
        return change_password_layout
    elif current_pathname == '/dash/user-manage':
        return user_manage_layout
    # 设备详情页面
    elif current_pathname == '/dash/equipment/detail':
        from urllib.parse import urlparse, parse_qs
        device_id = None
        # 确保 search 参数存在且不为空
        if current_search:
            from urllib.parse import parse_qs
            # 解析查询参数，例如 '?id=123'
            query_params = urlparse(current_search).query
            parsed_query = parse_qs(query_params)
            # 从解析结果中获取 'id' 参数的值
            device_id_list = parsed_query.get('id', [])
            if device_id_list:
                 device_id = device_id_list[0]

            # 尝试将 device_id 转换为整数，如果需要的话
            try:
                device_id = int(device_id)
            except (ValueError, TypeError):
                device_id = None # 如果转换失败，设为 None

        # 调用新的布局函数，传入设备ID
        return create_detail_layout(device_id=device_id)
    else:
        return html.Div([
            html.H1("404 - 页面不存在", className="text-center")
        ], style={'textAlign': 'center', 'marginTop': '50px'})




@server.route('/dash/logout')
def logout():
    session.clear()  # 清除所有session
    return redirect('/dash/login')




if __name__ == '__main__':
    dash_app.run(host='0.0.0.0', port=80)



